package nioTest.com.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;

/**
 * @author      : yang.xp
 * @date        : 2022/3/14 0014 20:13
 * @description : 文件的copy
 */
public class NIOFileChannel03 {

    public static void main(String[] args) {

        try {
            FileInputStream fileInputStream = new FileInputStream("./log/test.log");
            FileOutputStream fileOutputStream = new FileOutputStream("./log/testCopy.log");
            ByteBuffer buffer = ByteBuffer.allocate(50);
            while (true) {
//              如果没有clear，buffer 里面可以读入的字节位0，就不能退出循环了。读入到buffer字节的数值
                buffer.clear();
                int read = fileInputStream.getChannel().read(buffer);
                System.out.println("read = " + read);
                if (read == -1) {
                    break;
                }
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, read));
                fileOutputStream.getChannel().write(buffer);
            }

            fileOutputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
